<?php

namespace app\admin\model\course;

use basic\BaseModel;
use services\PHPExcelService;
use traits\ModelTrait;

/**
 * @title 课模型
 * Class Course
 * @package app\admin\model\course
 */
class Course extends BaseModel
{
    use ModelTrait;

    /**
     * 主键ID
     * @var string
     */
    protected $pk = "id";

    /**
     * 模型名称
     * @var string
     */
    protected $name = "course";

    /**
     * @title 获取所有的课程
     * @param array $where
     */
    public static function courseList(array $where)
    {
        // 设置分页数据以及类型
        $model = self::getModelObject($where);
        if ($where['excel'] == 0) $model = $model->page((int)$where['page'], (int)$where['limit']);
        $data = ($data = $model->select()) && count($data) ? $data->toArray() : [];
        if ($where["excel"] == 1) {
            $export = [];
            foreach ($data as $index => $item) {
                $course_type = $item["course_type"];
                if ($course_type == 10) $course_type_value = "团体课";
                elseif ($course_type == 20) $course_type_value = "私教课";
                else $course_type_value = "直播课";
                $export[] = [
                    $item['id'],
                    $item['course_name'],
                    $course_type_value,
                    '￥' . $item['price'],
                    date("Y-m-d H:i:s", $item['add_time']),
                    $item['give_integral'],
                    $item['difficulty'],
                    $item['duration']
                ];
            }
            PHPExcelService::setExcelHeader(['课程ID', '课程名称', '课程类型', '学员价格', '添加时间', '赠送积分', '难度', '时长'])
                ->setExcelTile('课程导出', '课程信息' . time(), ' 生成时间：' . date('Y-m-d H:i:s', time()))
                ->setExcelContent($export)
                ->ExcelSave();
        }
        $count = $model->count();
        return compact('count', 'data');
    }

    /**
     * 获取模型对象
     * @param array $where
     * @return Course
     */
    public static function getModelObject($where = [])
    {
        $model = new self();
        $model = $model->where("course_type", "=", $where["course_type"]);
        if (!empty($where)) {
            if (isset($where["order"]) && $where["order"] != '') {
                $model = $model->order(self::setOrder($where['order']));
            } else {
                $model = $model->order('sort desc,id desc');
            }
        }
        $model = $model->where("is_del", "=", 0)->where("wxapp_id", "=", self::$wxapp_id);
        return $model;
    }
}